package com.hzit.pay.center.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.extra.ftp.Ftp;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.hzit.pay.center.config.PayCenterConfig;
import com.hzit.pay.center.model.PaySerialNoInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * 实现支付宝的接口
 *
 */
@Component
public class AlipayUtil {

    /**
     * 配置中心
     */
    @Autowired
    private PayCenterConfig payCenterConfig;

    private Logger logger = LoggerFactory.getLogger(AlipayUtil.class);

    /**
     * 支付宝PC支付
     * @param paySerialNoInfo
     * @return
     * @throws AlipayApiException
     */
    public String alipayPagePayment(PaySerialNoInfo paySerialNoInfo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getAlipayServiceUrl(),
                payCenterConfig.getAlipayAppId(),payCenterConfig.getPrivateKey(), payCenterConfig.getAlipayFormat(),
                payCenterConfig.getAlipayCharSet(),payCenterConfig.getAlipayPubKey(),payCenterConfig.getAlipaySignType());


        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        JSONObject object = new JSONObject();

        object.put("out_trade_no",paySerialNoInfo.getPaySerialNumber());
        object.put("product_code",payCenterConfig.getAlipayPageProductCode()); //TODO

        String subject = paySerialNoInfo.getGoodsDesc();
        String payAmount = paySerialNoInfo.getPayAmount().toString();

        logger.info("subject = " + subject + "茅台".equals(subject));
        logger.info("payAmount = " + payAmount + "100".equals(payAmount));


        object.put("subject",subject);
        object.put("total_amount",payAmount);


        request.setBizContent(object.toJSONString());

        request.setNotifyUrl(payCenterConfig.getNotifyUrl()); //异步回调（后端回调），支付成功触发。主要用来修改订单的状态。
        request.setReturnUrl("http://www.baidu.com"); //前端回调，用于支付成功后的页面跳转

        AlipayTradePagePayResponse  response = alipayClient.pageExecute(request);

        String payUrl = response.getBody();

        logger.info("支付宝返回的url：{}",payUrl);
        return payUrl;

    }


    /**
     * 支付宝支付结果查询
     * @param paySerialNoInfo
     * @return
     * @throws AlipayApiException
     */
    public AlipayTradeQueryResponse alipayPayQuery(PaySerialNoInfo paySerialNoInfo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getAlipayServiceUrl(),
                payCenterConfig.getAlipayAppId(),payCenterConfig.getPrivateKey(), payCenterConfig.getAlipayFormat(),
                payCenterConfig.getAlipayCharSet(),payCenterConfig.getAlipayPubKey(),payCenterConfig.getAlipaySignType());

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("out_trade_no",paySerialNoInfo.getPaySerialNumber());
        jsonObject.put("trade_no",paySerialNoInfo.getRespSerialNumber());

        request.setBizContent(jsonObject.toJSONString());

        AlipayTradeQueryResponse response = alipayClient.execute(request);

        return response;
    }

    /**
     * 支付宝退款接口：同步退款
     */
    public AlipayTradeRefundResponse alipayRefund(){

        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getAlipayServiceUrl(),
                payCenterConfig.getAlipayAppId(),payCenterConfig.getPrivateKey(), payCenterConfig.getAlipayFormat(),
                payCenterConfig.getAlipayCharSet(),payCenterConfig.getAlipayPubKey(),payCenterConfig.getAlipaySignType());

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject bizObject = new JSONObject();
        bizObject.put("out_trade_no","1370296366496092160");
        bizObject.put("trade_no","2021031222001403780501470984");

        bizObject.put("refund_amount","100");


        request.setBizContent(bizObject.toJSONString());

        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);


        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(response.isSuccess()){
            System.out.println("======getCode===="+ response.getCode());
            System.out.println("========getMsg===" + response.getMsg() );

            System.out.println("=========getSubCode==" + response.getSubCode() );
            System.out.println("=========getSubMsg==" + response.getSubMsg() );

            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return response;
    }

    /**
     * 获取对账文件
     * @return
     */
    public String getReconFile (String reconDate) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getAlipayServiceUrl(),
                payCenterConfig.getAlipayAppId(),payCenterConfig.getPrivateKey(), payCenterConfig.getAlipayFormat(),
                payCenterConfig.getAlipayCharSet(),payCenterConfig.getAlipayPubKey(),payCenterConfig.getAlipaySignType());

        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();//创建API对应的request类

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("bill_date",reconDate);
        jsonObject.put("bill_type","trade");

        request.setBizContent(jsonObject.toJSONString());

        AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类

        String downUrl = response.getBillDownloadUrl();

        //存在 liunx的路径
        String filePath = "local/temp/+ " +reconDate +".zip";

        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            url = new URL(downUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setConnectTimeout(5 * 1000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
            httpUrlConnection.connect();
            fis = httpUrlConnection.getInputStream();
            byte[] temp = new byte[1024];
            int b;
            fos = new FileOutputStream(new File(filePath));
            while ((b = fis.read(temp)) != -1) {
                fos.write(temp, 0, b);
                fos.flush();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fis!=null) fis.close();
                if(fos!=null) fos.close();
                if(httpUrlConnection!=null) httpUrlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        //文件服务器的地址
        Ftp ftp = new Ftp("192.168.1.121",888,"root","12345");

        //                  文件服务器路径     上传的文件

        String destPath = "local/file";
        boolean flag = ftp.upload(destPath,new File(filePath));

        if (flag){
            //成功 ，删除本地文件
            return destPath;

        }

        return null;

    }





}
